package com.game.net.server.http;

import com.game.net.BaseServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class HttpServer extends BaseServer {
	public static boolean isSSL = true;
	private Logger logger = LoggerFactory.getLogger(HttpServer.class);
	private int port;

	public void init(int port, final SimpleChannelInboundHandler handler) {
		this.port = port;
		logger.info("start server");
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.childHandler(new HttpServerInitializer());
			Channel ch = b.bind(port).sync().channel();
			System.out.println("HTTP Upload Server at port " + port + '.');
			System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

			ch.closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public HttpServer() {
	}
}
